"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-tft-research
"""
from machine import ADC, Pin, Timer # , ADCBLOCK
from config import Config


class Directions(object):
	NONE = 0
	CENTER = 1
	LEFT = 2
	RIGHT = 3
	UP = 4
	DOWN = 5

	DIRECTIONS = {
		CENTER: [1440, 1450],
		LEFT: [1350, 1370],
		RIGHT: [330, 370],
		UP: [570, 590],
		DOWN: [1080, 1100]
	}


class FiveDirectionButton_ADC(object):
	def __init__(self, adc_pin):
		self.__adc = ADC(Pin(adc_pin))
		self.__adc.atten(ADC.ATTN_11DB)
		# self.__adc = ADCBLOCK(0, bits=12)
		# self.__adc.connect(1, Pin(Config.Pins.ADC))

	@property
	def direction(self):
		sample_avg = 0

		for _ in range(20):
			sample_avg += self.__adc.read()
		
		sample_avg = int(sample_avg / 20)

		if sample_avg == 4095:
			return
		
		for direction, _range in Directions.DIRECTIONS.items():
			if _range[0] <= sample_avg <= _range[1]:
				return direction
		
		return Directions.NONE

	def scan(self):
		timer = Timer(0)

		timer.init(
			mode=Timer.PERIODIC,
			period=200,
			callback=self.__scan_cb
		)
	
	def __scan_cb(self, _):
		sample_avg = 0

		for _ in range(20):
			sample_avg += self.__adc.read()
			# sample_avg += self.__adc.read_uv()

		sample_avg = int(sample_avg / 20)

		if sample_avg == 4095:
			return

		print(f'avg value: {sample_avg}')
	

if __name__ == '__main__':
	button = FiveDirectionButton_ADC(Config.Pins.ADC)
	button.scan()
